package com.binarysoft.service.common.threadpool;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import common.framework.dsb.AbstractServiceBean;
import common.framework.dsb.annotation.DSBService;
import common.framework.dsb.service.ServiceContext;

/**
 * @author David
 * 
 */
@DSBService(name = "DSB/ThreadPoolService")
public class ThreadPoolServiceBean extends AbstractServiceBean implements ThreadPoolService {
	private ThreadPoolExecutor threadPoolExecutor = null;

	@Override
	public void start(ServiceContext serviceContext) throws Exception {
		super.start(serviceContext);
		serviceContext.loadConfigProperties("thread_pool.properties");

		int corePoolSize = Integer.parseInt(serviceContext.getProperty("core_pool_size"));
		int maximumPoolSize = Integer.parseInt(serviceContext.getProperty("maximum_pool_size"));
		long keepAliveTime = Long.parseLong(serviceContext.getProperty("keep_alive_time"));
		int capacity = Integer.parseInt(serviceContext.getProperty("queue_capacity"));
		TimeUnit unit = TimeUnit.SECONDS;
		BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<Runnable>(capacity);

		threadPoolExecutor = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue);
		threadPoolExecutor.prestartAllCoreThreads();
	}

	public void close() throws Exception {
		threadPoolExecutor.shutdown();
	}

	public void refresh() throws Exception {
	}

	public void execute(Runnable runnable) {
		// TODO Auto-generated method stub
		threadPoolExecutor.execute(runnable);
	}

	public int getQueueSize() {
		return threadPoolExecutor.getQueue().size();
	}

}
